//
//  RegistViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/16.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "FindPasswordViewController.h"
#import "LoginItem.h"
#import "MQVerCodeImageView.h"
#import "RootTabBarViewController.h"

@interface FindPasswordViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) LoginItem *phoneItem;
@property (nonatomic, strong) LoginItem *phoneItem1;
@property (nonatomic, strong) LoginItem *codeItem;
@property (nonatomic, strong) LoginItem *password1;
@property (nonatomic, strong) LoginItem *password2;
@property (nonatomic, strong) MQVerCodeImageView *codeImageView;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSString *tuXingcode;
@property (nonatomic, strong) NSString *seeTuXingCode;
@property (nonatomic, strong) UIButton *timeBtn;

@end

@implementation FindPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = navBarColor;
    
    [self getTuXingCode];
    [self.view addSubview:self.tableView];
    [self loadBaseTitleLable:@"忘记密码"];
    self.navTitleBgView.backgroundColor = kClearColor;
    [self.leftBtn addTarget:self action:@selector(backAction) forControlEvents:(UIControlEventTouchUpInside)];
}
- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 获取图形验证码
- (void)getTuXingCode
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/config/config.ashx?action=txyzm&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        
        if ([responseObject[@"status"] intValue] == 1) {
            self.tuXingcode = responseObject[@"code"];
        } else {
            
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.contentView.backgroundColor = UIColorWhite;
    WeakSelf
    if (indexPath.row == 0) {
        self.phoneItem = [[LoginItem alloc] init];
        _phoneItem.textField.textColor = UIColorFromRGB(0x323232);
        _phoneItem.line.backgroundColor = globalGray;
        _phoneItem.textField.placeholder = @"请输入手机号...";
        _phoneItem.icon.image = UIImageNamed(@"registshouji");
        [cell.contentView addSubview:_phoneItem];
        [_phoneItem mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell.contentView);
            make.size.mas_offset(CGSizeMake(kScreenWidth, rateHeight(90)));
            make.top.equalTo(cell.contentView);
        }];
        UIButton *getCodeBtn = [UIButton buttonWithTitle:@"获取验证码" fontSize:13 titleColor:UIColorWhite background:navBarColor cornerRadius:3];
        [_phoneItem addSubview:getCodeBtn];
        [getCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.phoneItem.line);
            make.bottom.equalTo(weakSelf.phoneItem);
            make.size.mas_offset(CGSizeMake(rateWidth(200), rateHeight(90)));
        }];
        self.timeBtn = getCodeBtn;
        [self.timeBtn addTarget:self action:@selector(getPhoneCode) forControlEvents:(UIControlEventTouchUpInside)];
        
    } else if (indexPath.row == 1) {
        self.codeItem = [[LoginItem alloc] init];
        _codeItem.textField.textColor = UIColorFromRGB(0x323232);
        _codeItem.line.backgroundColor = globalGray;
        _codeItem.textField.placeholder = @"请输入验证码...";
        _codeItem.icon.image = UIImageNamed(@"registyanzhengma");
        [cell.contentView addSubview:_codeItem];
        [_codeItem mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell.contentView);
            make.size.mas_offset(CGSizeMake(kScreenWidth, rateHeight(90)));
            make.top.equalTo(cell.contentView);
        }];
    } else if (indexPath.row == 2) {
        self.password1 = [[LoginItem alloc] init];
        _password1.textField.textColor = UIColorFromRGB(0x323232);
        _password1.line.backgroundColor = globalGray;
        _password1.textField.placeholder = @"请输入密码(6-18位)...";
        _password1.textField.secureTextEntry = YES;
        _password1.icon.image = UIImageNamed(@"registsuo");
        [cell.contentView addSubview:_password1];
        [_password1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell.contentView);
            make.size.mas_offset(CGSizeMake(kScreenWidth, rateHeight(90)));
            make.top.equalTo(cell.contentView);
        }];
        
    } else if (indexPath.row == 3) {
        self.password2 = [[LoginItem alloc] init];
        _password2.textField.textColor = UIColorFromRGB(0x323232);
        _password2.line.backgroundColor = globalGray;
        _password2.textField.placeholder = @"确认密码(6-18位)...";
        _password2.textField.secureTextEntry = YES;
        _password2.icon.image = UIImageNamed(@"registsuo");
        [cell.contentView addSubview:_password2];
        [_password2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell.contentView);
            make.size.mas_offset(CGSizeMake(kScreenWidth, rateHeight(90)));
            make.top.equalTo(cell.contentView);
        }];
    } else {
        self.phoneItem1 = [[LoginItem alloc] init];
        _phoneItem1.textField.textColor = UIColorFromRGB(0x323232);
        _phoneItem1.line.backgroundColor = globalGray;
        _phoneItem1.textField.placeholder = @"请输入验证码...";
        _phoneItem1.icon.image = UIImageNamed(@"registyanzhengma");
        [cell.contentView addSubview:_phoneItem1];
        [_phoneItem1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell.contentView);
            make.size.mas_offset(CGSizeMake(kScreenWidth, rateHeight(90)));
            make.top.equalTo(cell.contentView);
        }];
        _codeImageView = [[MQVerCodeImageView alloc] initWithFrame:CGRectMake(0, 0, rateWidth(200), rateHeight(90))];
        _codeImageView.bolck = ^(NSString *imageCodeStr){//看情况是否需要
            NSLog(@"imageCodeStr = %@",imageCodeStr);
            weakSelf.seeTuXingCode = imageCodeStr;
        };
        _codeImageView.isRotation = NO;
        [_codeImageView freshVerCode];
        
        //点击刷新
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [_codeImageView addGestureRecognizer:tap];
        [_phoneItem1 addSubview: _codeImageView];
        [_codeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.phoneItem1.line);
            make.bottom.equalTo(weakSelf.phoneItem1);
            make.size.mas_offset(CGSizeMake(rateWidth(200), rateHeight(90)));
        }];
        
    }
    cell.selectionStyle = NO;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return rateHeight(90);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return rateHeight(450)+SafeAreaTopHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return rateHeight(320);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    bgV.backgroundColor = UIColorWhite;
    WeakSelf
    UIImageView *bgImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateHeight(430)+SafeAreaTopHeight)];
    bgImg.image = UIImageNamed(@"loginbgimg");
    [bgV addSubview:bgImg];
    bgImg.userInteractionEnabled = YES;
    UIImageView *headBgImg = [[UIImageView alloc] init];
    headBgImg.image = UIImageNamed(@"headquan");
    [headBgImg sizeToFit];
    [bgImg addSubview:headBgImg];
    [headBgImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgImg).offset(SafeAreaTopHeight+rateHeight(20));
        make.centerX.equalTo(bgImg);
    }];
    headBgImg.userInteractionEnabled = YES;
    
    UIImageView *headImg = [[UIImageView alloc] init];
    headImg.image = UIImageNamed(@"headImgdefault");
    headImg.layer.cornerRadius = rateHeight(110);
    [bgImg addSubview:headImg];
    [headImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(headBgImg);
        make.size.mas_offset(CGSizeMake(rateHeight(220), rateHeight(220)));
    }];
    headImg.userInteractionEnabled = YES;
    
    return bgV;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    bgV.backgroundColor = UIColorWhite;
    WeakSelf
    UIButton *registBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [registBtn setImage:UIImageNamed(@"findpwqueding") forState:(UIControlStateNormal)];
    [registBtn sizeToFit];
    [bgV addSubview:registBtn];
    [registBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgV).offset(rateHeight(70));
        make.centerX.equalTo(bgV);
    }];
    [registBtn addTarget:self action:@selector(registAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    return bgV;
}
- (void)tapClick:(UITapGestureRecognizer*)tap
{
    [_codeImageView freshVerCode];
    [self getTuXingCode];
}
#pragma mark - 设置新密码
- (void)registAction
{
    NSLog(@"%@-----%@",self.phoneItem1.textField.text,self.seeTuXingCode);
    if (self.codeItem.textField.text.length != 0) {
        
        if ([self.phoneItem1.textField.text isEqualToString:self.seeTuXingCode]) {
            [self zhuCe];
        } else {
            [TFHUD addRemindHUD:self.view message:@"图形验证码输入有误"];
        }
    } else {
        [TFHUD addRemindHUD:self.view message:@"请输入手机验证码"];
    }
}
- (void)zhuCe
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=getpass&chktype=106&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"chkData1":self.phoneItem.textField.text,@"chkData2":self.password1.textField.text,@"chkData3":self.password2.textField.text} success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if (responseObject) {
            
            if ([responseObject[@"status"] intValue] == 1) {
                if ([responseObject[@"chkType"] intValue] == 0) {
                    [MBProgressHUD showSuccess:@"密码重置成功"];
                    [self dismissViewControllerAnimated:YES completion:nil];
                } else if ([responseObject[@"chkType"] intValue] == 1) {
                    [TFHUD addRemindHUD:self.view message:@"重设密码失败，校验码已失效"];
                } else if ([responseObject[@"chkType"] intValue] == 2) {
                    [TFHUD addRemindHUD:self.view message:@"重设密码失败，校验码不正确"];
                } else if ([responseObject[@"chkType"] intValue] == 3) {
                    [TFHUD addRemindHUD:self.view message:@"重设密码失败，密码必须6-18位"];
                } else if ([responseObject[@"chkType"] intValue] == 4) {
                    [TFHUD addRemindHUD:self.view message:@"重设密码失败，密码与确认密码不能为空"];
                } else if ([responseObject[@"chkType"] intValue] == 5) {
                    [TFHUD addRemindHUD:self.view message:@"重设密码失败，密码与确认密码不一致"];
                } else if ([responseObject[@"chkType"] intValue] == 6) {
                    [TFHUD addRemindHUD:self.view message:@"重设密码失败，密码重置超时"];
                } else if ([responseObject[@"chkType"] intValue] == 7) {
                    [TFHUD addRemindHUD:self.view message:@"重设密码失败，您使用了错误的提交方式"];
                }
                
                
            }
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
    }];
}
#pragma mark - 获取验证码
- (void)getPhoneCode
{
    if (self.phoneItem.textField.text.length == 11) {
        [self getCodeRequest]; // 注册获取验证码
    } else {
        [TFHUD addRemindHUD:self.view message:@"请输入正确的手机号"];
    }
}
- (void)getCodeRequest
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=getpass&chktype=102&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"chkData1":self.phoneItem.textField.text,@"chkData2":self.tuXingcode} success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if (responseObject) {
            if ([responseObject[@"status"] intValue] == 1) {
                if ([responseObject[@"chkType"] intValue] == 0) {
                    [TFHUD addRemindHUD:self.view message:@"发送成功，请查看您的手机短信获取校验码"];
                    [self startTime];
                } else if ([responseObject[@"chkType"] intValue] == 1) {
                    [TFHUD addRemindHUD:self.view message:@"手机号不能为空"];
                } else if ([responseObject[@"chkType"] intValue] == 2) {
                    [TFHUD addRemindHUD:self.view message:@"手机账号格式不正确"];
                } else if ([responseObject[@"chkType"] intValue] == 3) {
                    [TFHUD addRemindHUD:self.view message:@"图形验证码超时"];
                } else if ([responseObject[@"chkType"] intValue] == 4) {
                    [TFHUD addRemindHUD:self.view message:@"图形验证码不正确"];
                } else if ([responseObject[@"chkType"] intValue] == 5) {
                    [TFHUD addRemindHUD:self.view message:@"发送失败，同一手机短信发送太频繁"];
                } else if ([responseObject[@"chkType"] intValue] == 6) {
                    [TFHUD addRemindHUD:self.view message:@"短信验证未启用"];
                } else if ([responseObject[@"chkType"] intValue] == 7) {
                    [TFHUD addRemindHUD:self.view message:@"手机号码不存在"];
                }
                
            } else {
                
            }
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
    }];
}
-(void)startTime
{
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置（倒计时结束后调用）
                [self.timeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
                //设置可点击
                self.timeBtn.userInteractionEnabled = YES;
                
            });
        }else{
            //            int minutes = timeout / 60;    //这里注释掉了，这个是用来测试多于60秒时计算分钟的。
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //                NSLog(@"____%@",strTime);
                [self.timeBtn setTitle:[NSString stringWithFormat:@"%@s",strTime] forState:(UIControlStateNormal)];
                //设置可点击
                self.timeBtn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -20, kScreenWidth, kScreenHeight+20) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = UIColorWhite;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
